/*
 * @Author: asushiye
 * @Date: 2020-07-02 15:30:23
 * @Commit: file content
 */

import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { AfMessageService } from '@core';
import { STColumn, STComponent } from '@delon/abc/st';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { AfOperType } from 'src/app/core/af/af-const';
import { AfExcelService, ExcelUploadRecord } from 'src/app/routes/system/excel/af-excel.service';
import { ExcelUploadComponent } from 'src/app/routes/system/excel/upload/excel-upload.component';

import { DataplatformService } from '../dataplatform.service';

@Component({
  selector: 'app-cg-dp-indicators-desc',
  templateUrl: './dp-indicators-desc.component.html'
})
export class DataplatformIndicatorsDescComponent implements OnInit {
  rows: any[] = [];
  queryParams: any = { indiAlias: '', indiName: '' };
  url = '';
  req = { params: this.queryParams, lazyLoad: false };

  isLoading = false;
  isExport = false;
  isImport = false;
  afOperType = AfOperType.add;
  databases: any[] = [];

  uploadRecord: ExcelUploadRecord = {
    currentQueueId: '',
    business: 'data_indicators',
    title: '中台指标',
    showExtendedFields: false,
    action: 'save',
    sourceId: '1',
    remark: ''
  };

  @ViewChild('st', { static: false }) st!: STComponent;
  columns: STColumn[] = [
    { title: '指标名', index: 'indiName' },
    { title: '指标实例名', index: 'indiAlias' },
    // { title: '描述', index: 'indiDesc' },
    // { title: '指标类型', index: 'indiType' },
    { title: '计算逻辑', index: 'calculationLogic' },
    { title: '统计范围', index: 'statisticalScope' },
    { title: '统计周期', index: 'statisticTime' },
    // { title: '负责人', index: 'responsiblePerson' },
    // { title: '计算周期', index: 'calculationPeriod' },
    {
      title: '启用状态',
      type: 'badge',
      index: 'enabled',
      badge: {
        0: { text: '禁用', color: 'default' },
        1: { text: '启用', color: 'success' }
      }
    },
    // { title: '更新人', index: 'lastModifiedBy' },
    // { title: '更新日期', index: 'lastModifiedDate' },
    {
      title: '操作',
      buttons: [
        {
          text: '历史变更',
          icon: 'history',
          tooltip: `历史变更`,
          click: _record => {
            this.openHistoryDrawer(_record);
          }
        },
        {
          text: '编辑',
          icon: 'edit',
          tooltip: `手动测试链接`,
          click: _record => {
            this.edit(_record);
          }
        },
        {
          text: '删除',
          icon: 'delete',
          type: 'del',
          tooltip: `删除此记录时，也会删除历史变更记录`,
          pop: {
            title: '执行此操作所有历史变更记录也会被删除， 您确定要删除此记录吗？',
            okType: 'danger',
            icon: 'star'
          },
          click: (record, _modal) => {
            this.delete(record);
          }
        }
      ]
    }
  ];

  @ViewChild('sth', { static: false }) sth!: STComponent;
  columnsHisotry: STColumn[] = [
    { title: '变更人', index: 'createdBy' },
    { title: '变更时间', index: 'createdDate' },
    // { title: '指标名', index: 'indiName' },
    // { title: '指标实例名', index: 'indiAlias' },
    // { title: '描述', index: 'indiDesc' },
    // { title: '指标类型', index: 'indiType' },
    { title: '计算逻辑', index: 'calculationLogic' },
    { title: '统计范围', index: 'statisticalScope' },
    { title: '统计周期', index: 'statisticTime' },
    // { title: '负责人', index: 'responsiblePerson' },
    // { title: '计算周期', index: 'calculationPeriod' },
    {
      title: '启用状态',
      type: 'badge',
      index: 'enabled',
      badge: {
        0: { text: '禁用', color: 'default' },
        1: { text: '启用', color: 'success' }
      }
    }
    // { title: '更新人', index: 'lastModifiedBy' },
    // { title: '更新日期', index: 'lastModifiedDate' },
  ];

  constructor(
    private cdr: ChangeDetectorRef,
    public msg: AfMessageService,
    private dpSrv: DataplatformService,
    private modal: ModalHelper,
    private excelSrv: AfExcelService
  ) {
    this.url = this.dpSrv.getIndicatorsUrl();
  }
  ngOnInit() {
    this.query();
  }

  public query() {
    console.log(JSON.stringify(this.queryParams));
    this.st?.reset(this.queryParams);
  }

  importData() {
    this.uploadRecord.currentQueueId = 0;
    const record = this.uploadRecord as any;
    this.modal.create(ExcelUploadComponent, { record }, { size: 'md' }).subscribe(res => {
      if (res.status) {
        this.uploadRecord.currentQueueId = res.data;
        this.query();
      }
    });
  }

  isExporting = false;
  exportData() {
    try {
      this.isExporting = true;
      this.excelSrv.exportData(this.uploadRecord, this.queryParams);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isExporting = false;
      }, 1500);
    }
  }

  isLogExporting = false;
  exportLog() {
    try {
      this.isLogExporting = true;
      this.excelSrv.exportLog(this.uploadRecord);
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
        this.isLogExporting = false;
      }, 1500);
    }
  }

  downloadTemplate() {
    this.cdr.detectChanges();
    try {
      this.excelSrv.downTemplateFile(this.uploadRecord);
    } finally {
      this.cdr.detectChanges();
    }
  }

  navUploadLogView() {
    this.excelSrv.navUploadLogView(this.uploadRecord);
  }

  delete(item: any) {
    try {
      this.dpSrv.delete(item.indiId).subscribe(body => {
        if (body.status) {
          this.rows = [];
          this.msg.notice_success('删除记录', `${item.indiAlias} 记录删除成功`);
          this.query();
        } else {
          this.msg.notice_warning('删除记录', `${item.indiAlias} 删除失败，警告编号${body.code};  警告信息${body.msg}`);
        }
      });
    } finally {
      setTimeout(() => {
        this.cdr.detectChanges();
      }, 200);
    }
  }

  autoTips: Record<string, Record<string, string>> = {
    'zh-cn': {
      required: '必填项'
    },
    en: {
      required: 'Input is required'
    }
  };

  tForm = new FormGroup({
    indiId: new FormControl(),
    indiName: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    indiAlias: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    indiDesc: new FormControl('', {}),
    indiType: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
    calculationLogic: new FormControl(''),

    statisticalScope: new FormControl('', {}),
    statisticTime: new FormControl('', {}),
    parentIds: new FormControl('', {}),
    calculationPeriod: new FormControl('', {}),
    responsiblePerson: new FormControl(''),

    enabled: new FormControl(1, { nonNullable: true, validators: [Validators.required] }),
    tags: new FormControl('', {})
  });

  drawerOption: any = { size: 'large', visible: false, title: '编辑' };
  openDrawer() {
    this.drawerOption.visible = true;
    if (this.afOperType == AfOperType.edit) {
      this.tForm.controls.indiName.disable();
      this.tForm.controls.indiAlias.disable();
    } else {
      this.tForm.controls.indiName.enable();
      this.tForm.controls.indiAlias.enable();
    }
  }

  closeDrawer() {
    this.drawerOption.visible = false;
  }

  save() {
    if (this.tForm.invalid) {
      this.msg.notice_warning('警告', '表单无效不能保存');
      return;
    }
    this.dpSrv.save(this.tForm.getRawValue()).subscribe(res => {
      if (res.status) {
        this.query();
        this.msg.notice_success('', '保存成功');
        this.closeDrawer();
      } else {
        this.msg.notice_warning('保存失败', res.msg);
      }
    });
  }

  add() {
    this.afOperType = AfOperType.add;
    this.tForm.reset();
    // this.tForm.controls.dbLinkType.disable();
    // this.tForm.controls.dbSchema.disable();
    this.openDrawer();
  }

  edit(item: any) {
    this.afOperType = AfOperType.edit;
    this.tForm.reset();
    this.tForm.patchValue(item);
    this.openDrawer();
  }

  drawerHistoryOption: any = { width: '90%', size: 'large', visible: false, title: '历史变更记录' };

  historyRows: any[] = [];
  openHistoryDrawer(record: any) {
    this.dpSrv.queryHistory(record.indiId).subscribe(res => {
      if (res.status) {
        this.historyRows = res.data;
        this.drawerHistoryOption.visible = true;
        this.drawerHistoryOption.title = `【${record.indiAlias}】历史变更记录`;
      } else {
        this.msg.notice_warning('保存失败', res.msg);
      }
    });
  }

  closeHistoryDrawer() {
    this.drawerHistoryOption.visible = false;
  }
}
